package com.shop.shopserver.handler;

import com.alibaba.fastjson.JSON;
import com.shop.shopcommon.properties.WebSecurityProperties;
import com.shop.shopcommon.result.Result;
import com.shop.shoppojo.vo.UserLoginSuccessVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import static com.shop.shopcommon.constant.MessageConstant.LOGIN_SUCCESS;

/**
 * 登录成功处理器
 */
@Component
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private WebSecurityProperties webSecurityProperties;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 处理成功登录后的逻辑
        // 设置自定义登录标识的 cookie
        // Cookie loginCookie = new Cookie(webSecurityProperties.getLoginCookieName(), "true");
        // loginCookie.setPath("/");
        // response.addCookie(loginCookie);

        // 登录成功处理逻辑，返回 JSON 响应
        response.setContentType("application/json;charset=UTF-8");
        // 获取用户信息
        System.out.println("authentication = " + authentication);
        UserLoginSuccessVO userLoginSuccessVO = new UserLoginSuccessVO();
        if (authentication != null && authentication.getPrincipal() instanceof User user) {
            userLoginSuccessVO = UserLoginSuccessVO.builder()
                    .phone(user.getUsername())
                    .token("")
                    .build();
        }
        // 调用 Result 类的 success 方法创建结果对象
        Result<UserLoginSuccessVO> result = Result.success(userLoginSuccessVO, LOGIN_SUCCESS);
        // 将结果对象转换为 JSON 字符串，并写入响应体中
        response.getWriter().write(JSON.toJSONString(result));
    }
}